<?php
date_default_timezone_set('PRC');
namespace Home\Controller;
use Common\Model\OrderModel;
class OrderController extends BaseController {
	//用户下单
    public function index()
    {
        if(IS_POST){
            $res = I('post.');
        	if(!session(id)){
        		$this->ajaxReturn(['code'=>0,'msg' => '未进行登录，无法下单，请前往下单']);
        	}
        	$orderid = date('YmdHis').rand(0,999999);
        	$where['eid'] = $res['eid'];//规格族ID
        	$where['eidname'] = $res['eidname'];//规格族ID
        	$where['orderid'] = $orderid;//订单号
        	$where['uid'] = session(id);//用户ID
        	$where['username'] = session(username);//用户名
            $where['password'] = $res['password'];//
            //实例的付费方式。取值范围：PrePaid：预付费，包年包月。选择该类付费方式时，您必须确认自己的账号支持余额支付/信用支付，否则将返回 InvalidPayMethod 的错误提示。PostPaid：按量付费。默认值：PostPaid
            if($res['jifei'] == 1){
                $where['jifei'] = "PrePaid";
            }else{
                $where['jifei'] = "PostPaid";
            }
        	$where['diyu'] = $res['diyu'];//地域
        	$area = M('area')->field('valuename')->where(['keyname'=>$where['diyu']])->find();
        	$where['diyuname'] = $area['valuename'];//地域
            if($res['xipan'] == "高效云盘"){
                $where['xipan'] = "cloud_efficiency";//系统盘
            }else{
                $where['xipan'] = "cloud_ssd";//系统盘
            }
        	$where['xipannei'] = $res['xipannei'];//系统盘内存

            $shujuinfo = array();
            foreach ($res['shuju'] as $key => $value) {
                if($value == "高效云盘"){
                    $value = "cloud_efficiency";
                }else{
                    $value = "cloud_ssd";
                }
                $shujuinfo[] = $value;
            }
            $where['shuju'] = join(',',$shujuinfo);//数据盘

            $shujuneiinfo = array();
            foreach ($res['shujunei'] as $key => $value) {
                $shujuneiinfo[] = $value;
            }
            $where['shujunei'] = join(',',$shujuneiinfo);//数据盘内存
            $where['money'] = $res['money'];//下单金额
            $where['ordertime'] = time();//下单时间
            $where['PeriodUnit'] = "Month";//购买资源的时长。可选值Week | Month。
            $where['Period'] = $res['time'];//时长
            $where['IoOptimized'] = "optimized";
            $where['InternetMaxBandwidthOut'] = $res['InternetMaxBandwidthOut'];//宽带
            //InternetChargeType网络计费类型。取值范围：PayByBandwidth：按固定带宽计费;PayByTraffic：按使用流量计费;默认值：PayByTraffic
            if($res['InternetChargeType'] == 1){
                $where['InternetChargeType'] = "PayByBandwidth";
            }else{
                $where['InternetChargeType'] = "PayByTraffic";
            }
            $where['ImageId'] = $res['ImageId'];
            $where['keys'] = 'yun'.date('YmdHis');
            $where['values'] = session(id);
            $where['zoneid'] = $res['zoneid'];

            $arra['agent_id'] = session(id);
            $arra['is_agent'] = 0;
            $usera = M('mid_relation')->where($arra)->find();
            if(!$usera){
                $usera['instance'] = 1;
                $usera['system_disk'] = 1;
                $usera['storage_disc'] = 1;
                $usera['network'] = 1;
            }
            $where['rulepid'] = $usera['instance'];
            $where['xipid'] = $usera['system_disk'];
            $where['shupid'] = $usera['storage_disc'];
            $where['widthpid'] = $usera['network'];

            $where['ruleprice'] = $res['ruleprice'];
            $where['xiprice'] = $res['xiprice'];
            $where['shuprice'] = $res['shuprice'];
            $where['widthprice'] = $res['widthprice'];
          /*  $where['num'] = 2;
        	$info = M('orders')->add($where);*/
            $info = M('order')->add($where);
        	if($info){
                $this->ajaxReturn(['code'=>1,'msg' => '下单成功,正前往支付','data'=>$where['orderid']]);
        	}else{
                $this->ajaxReturn(['code'=>0,'msg' => '下单失败']);
        	}
        }
    }

    public function cc()
    { 
        $url = "cn-qingdao";
        $cidrblock = "172.16.0.0/12";
        $vpcname = "dhtytuytujy";
        $description = "";
      /*  $info = $this->CreateVpc($url,$cidrblock,$vpcname,$description);*/
        $vpcid = "vpc-m5etbtcq3yg479g2hhu2u";
        $zoneid = "cn-qingdao-c";
        $cidrblock = "172.16.0.0/24";
        $vswitchname = "dfhtyuyyuyjuyiuy";
        $infos = $this->CreateVSwitch($url,$zoneid,$cidrblock,$vpcid,$vswitchname,$description);
        dump($infos);

        $a = $this->DescribeVSwitches("cn-qingdao");
        dump($a);

      /*   $a = $this->DescribeVpcs("cn-qingdao");
        dump($a);*/
    }

    public function gg()
    {
        $vinfo = $this->DeleteVSwitch("cn-qingdao","vsw-m5e3ef06i2wfxvyu2mm31");
    }

    //模拟GET请求
    public function curlget($url)
    {
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);  // 从证书中检查SSL加密算法是否存在
        $tmpInfo = curl_exec($curl);     //返回api的json对象
        //关闭URL请求
        curl_close($curl);
        $tmpInfo = json_decode($tmpInfo,true);
        return $tmpInfo;
    }

    //创建VPC
    public function CreateVpc($territory,$cidrblock,$vpcname,$description)
    {
        $values = aliyun();
        $url = 'http://'.$_SERVER['HTTP_HOST'].'/aliyuns/CreateVpc.php?url='.$territory.'&accesskeyid='.$values['accesskeyid'].'&accesssecret='.$values['accesssecret'].'&cidrblock='.$cidrblock.'&vpcname='.$vpcname.'&description='.$description;  
        $tmpInfo = $this->curlget($url);
  /*      $tmpInfo = $tmpInfo['Instances']['Instance'];*/
        return $tmpInfo;
    }

    //查询已创建的VPC
    public function DescribeVpcs($territory)
    {
        $values = aliyun();
        $url = 'http://'.$_SERVER['HTTP_HOST'].'/aliyuns/DescribeVpcs.php?url='.$territory.'&accesskeyid='.$values['accesskeyid'].'&accesssecret='.$values['accesssecret'];  
        $tmpInfo = $this->curlget($url);
        $tmpInfo = $tmpInfo['Vpcs']['Vpc'];
        return $tmpInfo;
    }
    
    //删除一个专有网络（VPC）
    public function DeleteVpc($territory,$vpcid)
    {
        $values = aliyun();
        $url = 'http://'.$_SERVER['HTTP_HOST'].'/aliyuns/DeleteVpc.php?url='.$territory.'&accesskeyid='.$values['accesskeyid'].'&accesssecret='.$values['accesssecret'].'&vpcid='.$vpcid;  
        $tmpInfo = $this->curlget($url);
/*        $tmpInfo = $tmpInfo['Vpcs']['Vpc'];*/
        return $tmpInfo;
    }

    //创建交换机
    public function CreateVSwitch($territory,$zoneid,$cidrblock,$vpcid,$vswitchname,$description)
    {
        $values = aliyun();
        $url = 'http://'.$_SERVER['HTTP_HOST'].'/aliyuns/CreateVSwitch.php?url='.$territory.'&accesskeyid='.$values['accesskeyid'].'&accesssecret='.$values['accesssecret'].'&zoneid='.$zoneid.'&cidrblock='.$cidrblock.'&vpcid='.$vpcid.'&vswitchname='.$vswitchname.'&description='.$description;  
        $tmpInfo = $this->curlget($url);
  /*      $tmpInfo = $tmpInfo['Instances']['Instance'];*/
        return $tmpInfo;
    }

    //查询已创建的交换机
    public function DescribeVSwitches($territory)
    {
        $values = aliyun();
        $url = 'http://'.$_SERVER['HTTP_HOST'].'/aliyuns/DescribeVSwitches.php?url='.$territory.'&accesskeyid='.$values['accesskeyid'].'&accesssecret='.$values['accesssecret'];  
        $tmpInfo = $this->curlget($url);
        $tmpInfo = $tmpInfo['VSwitches']['VSwitch'];
        return $tmpInfo;
    }

    //删除交换机
    public function DeleteVSwitch($territory,$vswitchid)
    {
        $values = aliyun();
        $url = 'http://'.$_SERVER['HTTP_HOST'].'/aliyuns/DeleteVSwitch.php?url='.$territory.'&accesskeyid='.$values['accesskeyid'].'&accesssecret='.$values['accesssecret'].'&vswitchid='.$vswitchid;  
        $tmpInfo = $this->curlget($url);
/*        $tmpInfo = $tmpInfo['Vpcs']['Vpc'];*/
        return $tmpInfo;
    }

    //查询指定地域的路由器列表
    public function DescribeVRouters($territory){
        $values = aliyun();
        $url = 'http://'.$_SERVER['HTTP_HOST'].'/aliyuns/DescribeVRouters.php?url='.$territory.'&accesskeyid='.$values['accesskeyid'].'&accesssecret='.$values['accesssecret'];  
        $tmpInfo = $this->curlget($url);
        $tmpInfo = $tmpInfo['VRouters']['VRouter'];
        return $tmpInfo;
    }

    //下单
    public function CreateInstance($url,$size,$category,$tagkey,$tagvalue,$instancetype,$imageid,$internetchargetype,$instancechargetype,$period,$periodunit,$setinternetmaxbandwidthout,$password,$setsystemdisksize,$setsystemdiskcategory,$zoneid){
        $values = aliyun();
        $url = 'http://'.$_SERVER['HTTP_HOST'].'/CreateInstance.php?url='.$url.'&accesskeyid='.$values['accesskeyid'].'&accesssecret='.$values['accesssecret'].'&size='.$size.'&category='.$category.'&tagkey='.$tagkey.'&tagvalue='.$tagvalue.'&imageid='.$imageid.'&instancetype='.$instancetype.'&internetchargetype='.$internetchargetype.'&instancechargetype='.$instancechargetype.'&period='.$period.'&periodunit='.$periodunit.'&periodunit='.$periodunit.'&setinternetmaxbandwidthout='.$setinternetmaxbandwidthout.'&password='.$password.'&setsystemdisksize='.$setsystemdisksize.'&setsystemdiskcategory='.$setsystemdiskcategory.'&zoneid='.$zoneid;  
        $tmpInfo = $this->curlget($url);
        return $tmpInfo;
    }



    //启动一台指定的实例。实例状态必须为 已停止（Stopped），才可以调用该接口。
    public function DescribeSecurityGroupAttribute($url,$instanceid)
    {
        $values = aliyun();
        $url = 'http://'.$_SERVER['HTTP_HOST'].'/aliyuns//DescribeSecurityGroupAttribute.php?url='.$url.'&accesskeyid='.$values['accesskeyid'].'&accesssecret='.$values['accesssecret'].'&instanceid='.$instanceid;  
        $tmpInfo = $this->curlget($url);
        return $tmpInfo;
    }

    //下单
    public function RunInstances($url,$size,$category,$tagkey,$tagvalue,$instancetype,$imageid,$internetchargetype,$instancechargetype,$period,$periodunit,$setinternetmaxbandwidthout,$password,$setsystemdisksize,$setsystemdiskcategory,$zoneid){
        $values = aliyun();
        $url = 'http://'.$_SERVER['HTTP_HOST'].'/aliyuns/RunInstances.php?url='.$url.'&accesskeyid='.$values['accesskeyid'].'&accesssecret='.$values['accesssecret'].'&size='.$size.'&category='.$category.'&tagkey='.$tagkey.'&tagvalue='.$tagvalue.'&imageid='.$imageid.'&instancetype='.$instancetype.'&internetchargetype='.$internetchargetype.'&instancechargetype='.$instancechargetype.'&period='.$period.'&periodunit='.$periodunit.'&periodunit='.$periodunit.'&setinternetmaxbandwidthout='.$setinternetmaxbandwidthout.'&password='.$password.'&setsystemdisksize='.$setsystemdisksize.'&setsystemdiskcategory='.$setsystemdiskcategory.'&zoneid='.$zoneid;  
        $tmpInfo = $this->curlget($url);
        return $tmpInfo;
    }

    
    //私网IP地址
    public function AllocatePublicIpAddress($territory,$instanceid)
    {
        $values = aliyun();
        $url = 'http://'.$_SERVER['HTTP_HOST'].'/AllocatePublicIpAddress.php?url='.$territory.'&accesskeyid='.$values['accesskeyid'].'&accesssecret='.$values['accesssecret'].'&instanceid='.$instanceid;  
        $tmpInfo = $this->curlget($url);
        $tmpInfo = $tmpInfo["IpAddress"];
        return $tmpInfo;
    }   

    //下单信息
    public function DescribeInstances($territory)
    {
        $values = aliyun();
        $url = 'http://'.$_SERVER['HTTP_HOST'].'/DescribeInstances.php?url='.$territory.'&accesskeyid='.$values['accesskeyid'].'&accesssecret='.$values['accesssecret'];  
        $tmpInfo = $this->curlget($url);
        $tmpInfo = $tmpInfo['Instances']['Instance'];
        return $tmpInfo;
    }

    //查询您已经创建的磁盘。
    public function DescribeDisks($territory,$instanceid)
    {
        $values = aliyun();
        $url = 'http://'.$_SERVER['HTTP_HOST'].'/DescribeDisks.php?url='.$territory.'&accesskeyid='.$values['accesskeyid'].'&accesssecret='.$values['accesssecret'].'&instanceid='.$instanceid;  
        $tmpInfo = $this->curlget($url);
        $tmpInfo = $tmpInfo['Disks']['Disk'];
        return $tmpInfo;
    }

    //微信支付成功修改状态
    public function notify()
    {
        if($_GET['orderid']){
            $urls = "http://".$_SERVER['HTTP_HOST'];
            if(!session(id)){
                $this->ajaxReturn(['code'=>0,'msg' => '未进行登录，无法下单，请前往下单','url'=>$urls."/index.php?m=home&c=login&a=index"]);
            }
            $orderid['orderid'] = $_GET['orderid'];
            $counts = M('order')->where($orderid)->find();
            $user = M('user')->field('money')->where('id='.$counts['uid'])->find();
            if($counts['money'] > $user['money']){
                $this->ajaxReturn(['code'=>0,'msg' => '金额不足,请前往充值','url'=>$urls."/index.php?m=home&c=recharge&a=index&money=".$counts['money']]);
            }
            if($counts['state'] == 0){
                $arr1['state'] = 1;
                $arrs1 = M('order')->where($orderid)->save($arr1);
                if($arrs1){
                    //下单
                    $res = $this->CreateInstance($counts['diyu'],$counts['shujunei'],$counts['shuju'],$counts['keys'],$counts['values'],$counts['eidname'],$counts['imageid'],$counts['internetchargetype'],$counts['jifei'],$counts['period'],$counts['periodunit'],$counts['internetmaxbandwidthout'],$counts['password'],$counts['xipannei'],$counts['xipan'],$counts['zoneid']);
                    /*$res['InstanceId'] = "i-8vbevr0yh0gzd8j2pls3";*/
                    if($res['InstanceId']){
                        $ins['InstanceId'] = $res['InstanceId'];
                        $ins['ins'] = 1;
                        $edit = M('order')->where($orderid)->save($ins);
                        if($edit){
                            $wheres = $this->yuninfo($orderid['orderid']);
                            $edit = M('order')->where($orderid)->save($wheres);
                            $order = M('order')->field('IpAddress')->where($orderid)->find();
                            if(empty($order['ipaddress'])){
                                $wheres = $this->yuninfo($orderid['orderid']);
                                $edit = M('order')->where($orderid)->save($wheres);
                            }
                            $count = M('order')->where($orderid)->find();
                            $infod  =  $this->DescribeDisks($count['diyu'],$count['instanceid']);
                            foreach ($infod as $key => $value) {
                                $arrs['uid'] = $count['uid'];
                                $arrs['oid'] = $count['id'];
                                $arrs['area'] = $count['diyu'];
                                $arrs['areaname'] = $count['diyuname'];
                                $arrs['rule'] =  $count['eidname'];
                                $arrs['InstanceId'] = $count['instanceid'];
                                $arrs['DiskChargeType'] = $value['DiskChargeType'];
                                $arrs['Device'] = $value['Device'];
                                $arrs['Type'] = $value['Type'];
                                $arrs['Size'] = $value['Size'];
                                $arrs['Portable'] = $value['Portable'];
                                $arrs['Status'] = $value['Status'];
                                $arrs['Category'] = $value['Category'];
                                $arrs['DiskId'] = $value['DiskId'];
                                $time = strtotime($value['CreationTime']);
                                $arrs['CreationTime'] = $time;
                                $info = M('disks')->add($arrs);
                            }
                            $users = M('user')->where('id='.$counts['uid'])->setDec('money',$counts['money']);
                            if($users){
                                $wherea['uid'] = session(id);//用户ID
                                $wherea['username'] = session(username);//用户名
                                $wherea['money'] = "-".$counts['money'];
                                $usera = M('user')->field('money')->where('id='.$wherea['uid'])->find();
                                $wherea['newmoney'] = $usera['money'];
                                $wherea['time'] = time();
                                $wherea['state'] = 2;
                                $wherea['pay'] = 1;
                                $infoa = M('water')->add($wherea);
                                $a = new OrderModel();
                                $a->getAgentCommissionByOrderId($orderid['orderid']);
                                if($infoa){
                                    $this->ajaxReturn(['code'=>1,'msg' => '下单成功','url'=>$urls."/index.php?m=home&c=recharge&a=rechargesuccess"]);
                                }else{
                                    $this->ajaxReturn(['code'=>0,'msg' => '下单失败','url'=>$urls."/index.php?m=home&c=service&a=index"]); 
                                }
                            }else{
                                $this->ajaxReturn(['code'=>0,'msg' => '下单失败','url'=>$urls."/index.php?m=home&c=service&a=index"]); 
                            }
                        }else{
                            $this->ajaxReturn(['code'=>0,'msg' => '下单失败','url'=>$urls."/index.php?m=home&c=service&a=index"]);
                        }
                    }else{
                        $ins['ins'] = 2;
                        $edit = M('order')->where($orderid)->save($ins);
                        $this->ajaxReturn(['code'=>0,'msg' => '下单失败','url'=>$urls."/index.php?m=home&c=service&a=index"]);
                    }
                }else{
                    $this->ajaxReturn(['code'=>0,'msg' => '下单失败','url'=>$urls."/index.php?m=home&c=service&a=index"]); 
                }
            }else{
                $this->ajaxReturn(['code'=>0,'msg' => '已经下单','url'=>$urls."/index.php?m=home&c=service&a=index"]); 
            }
        }     
    }

    //判断微信是否已经支付
    public function paystatus()
    {
        if(IS_POST){
            $where = I('post.');
            $count = M('order')->field('state')->where($where)->find();
            if($count['state'] == 1){
                $this->ajaxReturn(1);
            }
        }
    }

    public function dd()
    {
        $data['orderid'] = "20181114114806788970";
        $order = M('order')->field('IpAddress')->where($data)->find();
        $info = $this->yuninfo("20181114114806788970");
        dump($info);
        /*if($order['ipaddress']){
            dump($info);
        }else{
            dump(2);
        }*/
       
    }

    public function yuninfo($orderid)
    {
        $orderids['orderid'] = $orderid;
        $count = M('order')->where($orderids)->find();
        if($count['state'] == 1){
            $where['InstanceId'] = $count['instanceid'];
            $infos = $this->DescribeInstances($count['diyu']);
            foreach ($infos as $key => $value) {
                if($value['InstanceId'] == $where['InstanceId']){   
                    $where['InternetMaxBandwidthIn'] = $value['InternetMaxBandwidthIn'];
                    $where['InstanceChargeType'] = $value['InstanceChargeType'];
                    $where['Memory'] = $value['Memory']/1024;
                    $where['Cpu'] = $value['Cpu'];
                    $where['IpAddress'] = $value['VpcAttributes']['PrivateIpAddress']['IpAddress'][0];
                    $where['OSName'] = $value['OSName'];
                    $where['InstanceName'] = $value['InstanceName'];
                    $where['HostName'] = $value['HostName'];
                    $where['Status'] = $value['Status'];
                    $time = strtotime($value['CreationTime']);
                    $where['CreationTime'] = $time;
                }
            }

            $where['pay'] = 0;
            $where['state'] = 1;
            $where['endtime'] = time();
            $infod = $this->AllocatePublicIpAddress($count['diyu'], $count['instanceid']);
            $where['gongip'] = $infod;
            return $where;
        }
    }

    public function aa()
    {
        $a = ['i-8vbevr0yh0gzd8j2pls3','i-8vb7n2yed2vdkbyqhzif'];
        $res = array();
        foreach ($a as $key => $value) {
            $res[] = $value;
        }
        $ins = join(',',$res);
        $data['orderid'] = "20181114174546268127";
        $order = M('orders')->where($data)->find();
        $insid = explode(',', $order['instanceid']);
        foreach ($insid as $key => $value) {
            $arr = $this->instanceid($order['diyu'],$value);
            $arr['eid'] = $order['eid'];
            $arr['orderid'] = $order['orderid'];
            $arr['uid'] = $order['uid'];
            $arr['username'] = $order['username'];
            $arr['password'] = $order['password'];
            $arr['instanceid'] = $value;
            $infod  =  $this->DescribeDisks($order['diyu'],$value);
            $disk = $this->diskinfo($order,$infod,$value);
            dump($disk);
           /* $sql = M('orderinfo')->add($arr); */
        }
      /*  for ($i=0; $i <$order['num'] ; $i++) { 
            $arr['eid'] = $order['eid'];
            dump($arr);
        }*/


    }
    
    //多台实例信息匹配
    public function instanceid($diyu,$instanceid)
    {
        $infos = $this->DescribeInstances($diyu);
        foreach ($infos as $key => $value) {
            if($value['InstanceId'] == $instanceid){   
                $where['InternetMaxBandwidthIn'] = $value['InternetMaxBandwidthIn'];
                $where['InstanceChargeType'] = $value['InstanceChargeType'];
                $where['Memory'] = $value['Memory']/1024;
                $where['Cpu'] = $value['Cpu'];
                $where['IpAddress'] = $value['VpcAttributes']['PrivateIpAddress']['IpAddress'][0];
                $where['OSName'] = $value['OSName'];
                $where['InstanceName'] = $value['InstanceName'];
                $where['HostName'] = $value['HostName'];
                $where['Status'] = $value['Status'];
                $time = strtotime($value['CreationTime']);
                $where['CreationTime'] = $time;
            }
        }

        $where['pay'] = 0;
        $where['state'] = 1;
        $where['endtime'] = time();
        $infod = $this->AllocatePublicIpAddress($diyu, $instanceid);
        $where['gongip'] = $infod;
        return $where;
    }

    //磁盘信息
    public function diskinfo($count,$infod,$instanceid)
    {
        $count = M('order')->where($orderid)->find();
      /*  $infod  =  $this->DescribeDisks($count['diyu'],$count['instanceid']);*/
        foreach ($infod as $key => $value) {
            $arrs['uid'] = $count['uid'];
            $arrs['oid'] = $count['orderid'];
            $arrs['area'] = $count['diyu'];
            $arrs['areaname'] = $count['diyuname'];
            $arrs['rule'] =  $count['eidname'];
            $arrs['InstanceId'] = $instanceid;
            $arrs['DiskChargeType'] = $value['DiskChargeType'];
            $arrs['Device'] = $value['Device'];
            $arrs['Type'] = $value['Type'];
            $arrs['Size'] = $value['Size'];
            $arrs['Portable'] = $value['Portable'];
            $arrs['Status'] = $value['Status'];
            $arrs['Category'] = $value['Category'];
            $arrs['DiskId'] = $value['DiskId'];
            $time = strtotime($value['CreationTime']);
            $arrs['CreationTime'] = $time;
            $res = M('diskinfo')->where(['InstanceId'=>$arrs['InstanceId']])->find();
            if(!$res){
                $info = M('diskinfo')->add($arrs);
            }else{
                M('diskinfo')->where(['InstanceId'=>$arrs['InstanceId']])->save($arrs);
            }    
        }
    }
}